package cn.flying.cloud.base.core.log4j2;

import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.lookup.AbstractLookup;
import org.apache.logging.log4j.core.lookup.StrLookup;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

/**
 * 配置日志中可以读取环境变量
 *
 * @author: admin
 * @date: 2024年09月25日 10:05
 * @version: 1.0
 */
@Component
@Plugin(name = "spring", category = StrLookup.CATEGORY)
public class SpringEnvironmentLookup extends AbstractLookup implements ApplicationContextInitializer<ConfigurableApplicationContext> {

    private static ConfigurableApplicationContext context;

    @Override
    public String lookup(String key) {
        if (context != null) {
            return context.getEnvironment().getProperty(key);
        }
        return null; // 或者返回其他处理方式
    }

    @Override
    public String lookup(LogEvent event, String key) {
        // 这里可以使用 event 来获取更多的上下文信息，但通常我们不需要
        return lookup(key);
    }

    /**
     * Initialize the given application context.
     *
     * @param applicationContext the application to configure
     */
    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
        context = applicationContext;
    }
}